package com.gm.wholesale.module.order.ui;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.gm.commonlib.base.baseBean.BaseFragmentInfo;
import com.gm.commonlib.base.baseui.baseFragment.BaseFragment;
import com.gm.commonlib.base.baseui.baseListviewUI.BaseListFragment;
import com.gm.commonlib.module.evenbus.EventMessage;
import com.gm.commonlib.util.timeUtils.DateTimeUtils;
import com.gm.commonlib.views.timePickerView.TimePickerViewUtils;
import com.gm.commonlib.views.timePickerView.listener.OnTimeSelectListener;
import com.gm.wholesale.R;
import com.gm.wholesale.module.evenbus.EventBusType;
import com.gm.wholesale.module.config.ConfigData;
import com.gm.wholesale.module.order.adapter.ViewPagerAdapter;
import com.gm.wholesale.module.order.bean.OrderBean;
import com.gm.wholesale.module.order.bean.OrderDetailBean;
import com.gm.wholesale.module.order.bean.needorder.NeedOrderBean;
import com.gm.wholesale.module.order.interfaces.ISearchOrderByTime;
import com.gm.wholesale.module.order.listener.MyOnPageChangeListener;
import com.gm.wholesale.module.order.listener.MyOnTabSelectedListener;
import com.gm.wholesale.module.order.ui.needOrder.NeedOrderListFragment;
import com.gm.wholesale.module.order.view.orderManger.NeedOrderDetailView;
import com.gm.wholesale.module.order.view.orderManger.OrderDetailView;
import com.gm.wholesale.view.tabview.TabView;
import com.gm.wholesale.util.ViewUtil;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OrderMangerFragment extends BaseFragment {
    private OrderListFragment orderListFragment;
    private NeedOrderListFragment needOrderFragment;

    private OrderDetailView mOrderDetailView;

    private NeedOrderDetailView mNeedOrderDetailView;
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    TextView choiceTimeTv;
    private LinearLayout orderDetailLin;

    public ViewPagerAdapter mAdapter;

    private String mOrderingTimeBegin;
    private String mOrderingTimeEnd;

    private ViewPagerAdapter mViewPagerAdapter;
    public int mCurrentTabPos;

    private TabView OrderTabView;
    private TabView needOrderTabView;

    private void resetData(){
        mOrderingTimeBegin=null;
        mCurrentTabPos=0;
    }

    @Override
    protected void onCreateContentBody(ViewGroup parent) {
        View view = LayoutInflater.from(context).inflate(R.layout.fragment_order_manger, parent);
        initView(view);
    }


    private void initView(View view) {
        mTabLayout = view.findViewById(R.id.tabLayout);
        mViewPager = view.findViewById(R.id.viewPager);
        orderDetailLin = view.findViewById(R.id.orderDetailLin);
        mTabLayout.setupWithViewPager(mViewPager);
        mAdapter = getAdapter();
        //给ViewPager设置适配器
        mViewPager.setAdapter(mAdapter);
        mViewPager.setSaveEnabled(false);
        mViewPager.setOffscreenPageLimit(10);
        //将TabLayout和ViewPager关联起来
        mTabLayout.setupWithViewPager(mViewPager);

        //添加tab 自定义view
        TabLayout.Tab tab = mTabLayout.getTabAt(0);
        OrderTabView = new TabView(getActivity());
        tab.setCustomView(OrderTabView);
        OrderTabView.showView(ViewUtil.getString(getActivity(), R.string.tab_order_title));
        OrderTabView.showCheck();

        if (ConfigData.getConfigData().hasNeedOrderPermission()) {
            TabLayout.Tab tab2 = mTabLayout.getTabAt(1);
            needOrderTabView = new TabView(getActivity());
            needOrderTabView.showView(ViewUtil.getString(getActivity(), R.string.tab_need_order_title));
            tab2.setCustomView(needOrderTabView);
            mTabLayout.addOnTabSelectedListener(new MyOnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    ((TabView) tab.getCustomView()).showCheck();
                    mViewPager.setCurrentItem(tab.getPosition());
                }

                @Override
                public void onTabUnselected(TabLayout.Tab tab) {
                    ((TabView) tab.getCustomView()).showUnCheck();
                }

            });

            mViewPager.addOnPageChangeListener(new MyOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    mCurrentTabPos = position;
                    initTime();
                    if (needOrderFragment!=null){
                        needOrderFragment.getUnReviceOrderSize();
                    }
                    if (position == 1) { //需求单
                        needOrderFragment.updateView();
                    } else {
                        orderListFragment.updateView();
                    }
                }
            });
        } else {
            mTabLayout.setVisibility(View.GONE);
        }
        initSearchView(view);
    }

    private void initOrderDetail(){
        mOrderDetailView = new OrderDetailView(getActivity());
        //把view添加进去
        orderDetailLin.addView(mOrderDetailView);
    }


    private void initNeedOrderDetail(){
        mNeedOrderDetailView = new NeedOrderDetailView(getActivity());
        mNeedOrderDetailView.setOrderMangerFragment(this);
        orderDetailLin.addView(mNeedOrderDetailView);
    }

    private void initTime(){
        mOrderingTimeBegin=null;
        String time = DateTimeUtils.formatDateTime(System.currentTimeMillis(), DateTimeUtils.HMD2);
        choiceTimeTv.setText(time + "(今天)");
    }

    private void initSearchView(View view) {
        choiceTimeTv= view.findViewById(R.id.choiceTimeTv);
        initTime();
        choiceTimeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                long nowTime = System.currentTimeMillis();
                if (!TextUtils.isEmpty(mOrderingTimeBegin)) {
                    nowTime = DateTimeUtils.getTimeStringToLong(mOrderingTimeBegin, DateTimeUtils.LONG_DATETIME_FORMAT_STRING);
                }
                TimePickerViewUtils.showTimeByYMD(context, "选择时间", nowTime, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        mOrderingTimeBegin = DateTimeUtils.formatDateTime(date, DateTimeUtils.SHORT_DATETIME_FORMAT_STRING);
                        mOrderingTimeEnd = mOrderingTimeBegin + " 23:59:59";
                        mOrderingTimeBegin = mOrderingTimeBegin + " 00:00:00";
                        String time = DateTimeUtils.formatDateTime(date, DateTimeUtils.HMD2);
                        if (DateTimeUtils.isToday(date)) {
                            time = time + "(今天)";
                        }
                        choiceTimeTv.setText(time);
                        updateViewByTime(mOrderingTimeBegin, mOrderingTimeEnd);
                    }
                });
            }
        });
    }

    //todo 根据时间查询订单
    public void updateViewByTime(String begTime, String endTime) {
        ISearchOrderByTime iSearchOrderByTime = (ISearchOrderByTime) getCurrentFragment();
        iSearchOrderByTime.searchOrderByTime(begTime, endTime);
    }

    public BaseListFragment getCurrentFragment() {
        if (mCurrentTabPos == 0) {
            return orderListFragment;
        }
        return needOrderFragment;
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        super.onReceiveEvent(event);
        int type = event.getCode();
        //显示现场单子详情
        if (type == EventBusType.UPDATE_ORDER_DETAIL.getType()) {
            showOrderView((OrderBean) event.getData());
        }
        //显示需求单子详情
        else if (type == EventBusType.SHOW_NEED_ORDER_DETAIL.getType()) {
            showNeedOrderView((NeedOrderBean) event.getData());
        }
        //更新需求单子详情
        else if (type == EventBusType.UPDATE_NEED_ORDER_DETAIL.getType()) {
            showNeedOrderView((NeedOrderBean) event.getData());
        }
        //已点击打印，更新订单状态
        else if (type == EventBusType.IS_PRINT.getType()) {
            if (mNeedOrderDetailView==null)return;
            mNeedOrderDetailView.updateOrderState();
        }
    }


    public void hidOrderDetailView() {
        if (mOrderDetailView!=null){
            mOrderDetailView.setVisibility(View.GONE);
        }

    }

    public void hidNeedOrderDetailView() {
        if (mNeedOrderDetailView==null)return;
        mNeedOrderDetailView.setVisibility(View.GONE);
    }
    public void hasNotOrderData(){
        hidOrderDetailView();
        //刚进入订单管理。默认显示开单列表。隐藏需求单列表
        hidNeedOrderDetailView();
    }

    public void showRedUnReviceOrderSize(long size) {
        needOrderTabView.showNt(size);
    }


    //现场订单
    public void showOrderView(OrderBean orderBean) {
        hidNeedOrderDetailView();
        if (mOrderDetailView==null){
           initOrderDetail();
        }
        if (mOrderDetailView!=null){
            mOrderDetailView.showOrderDetail(orderBean);
        }

    }

    //需求单子
    public void showNeedOrderView(NeedOrderBean needOrderBean) {
        hidOrderDetailView();
        if (mNeedOrderDetailView==null){
            initNeedOrderDetail();
        }
        if (mNeedOrderDetailView!=null){
            mNeedOrderDetailView.showView(needOrderBean);
        }


    }

    public ViewPagerAdapter getAdapter() {
        List<BaseFragmentInfo> datas = new ArrayList<>();
        //订单列表
        orderListFragment = new OrderListFragment();
        orderListFragment.setOrderMangerFragment(this);
        orderListFragment.setIsGetData(true);
        datas.add(new BaseFragmentInfo(1, "订单", orderListFragment));

        if (ConfigData.getConfigData().hasNeedOrderPermission()) {
            //需求单列表
            needOrderFragment = new NeedOrderListFragment();
            //获取未截单数量
            needOrderFragment.getUnReviceOrderSize();
            needOrderFragment.setOrderMangerFragment(this);
            needOrderFragment.setIsGetData(false);
            datas.add(new BaseFragmentInfo(2, "需求单", needOrderFragment));
        }

        mViewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager(), datas);
        return mViewPagerAdapter;
    }


    public void removeFragment() {
        if (orderListFragment != null) {
            removeFragment(orderListFragment);
            orderListFragment=null;
        }
        if (needOrderFragment != null) {
            removeFragment(needOrderFragment);
            needOrderFragment=null;
        }

    }

    private void removeFragment(Fragment fragment) {
        getChildFragmentManager().beginTransaction().remove(fragment).commitAllowingStateLoss();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //todo 必须销毁它嵌套的相关fragment，不然下次添加会报错
        // todo因为子fragment没有销毁，还依附在当前fragment，不能再次被添加
        removeFragment(); //移除嵌套的fragment
        resetData();
        if (mNeedOrderDetailView!=null){
            mNeedOrderDetailView.destory();
        }
        mOrderDetailView=null;
        mNeedOrderDetailView=null;
    }


}
